package com.edu.edu.week_project01.activity.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.edu.edu.week_project01.R;
import com.edu.edu.week_project01.activity.Configs;
import com.edu.edu.week_project01.activity.FactoryFragment.FactoryFragment;
import com.edu.edu.week_project01.activity.adapter.MyPageAdapter;
import com.edu.edu.week_project01.activity.bean.FragmentBean;
import com.edu.edu.week_project01.activity.bean.ProgrameLiveDetailBean;
import com.edu.edu.week_project01.activity.utils.OkHttpUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 10/13 0013.
 */
public class ProgrameLiveDetailActivity extends AppCompatActivity implements View.OnClickListener{

    private VideoView mVideo;
    private ImageView iv_avator;
    private TextView tv_view;
    private TextView tv_nick;
    private TextView tv_title;
    private String uid;
    private List<String> list;

    private Handler mHandler = new Handler(){};
    private ProgrameLiveDetailBean bean;
    private String avator;
    private ArrayAdapter adapter;
    private Toolbar mBar;
    private UMShareAPI mShareAPI;
    private int view;
    private String title;
    private String nick;
    private ViewPager mVp;
    private TabLayout mTab;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.live_detail_list_item);
        //EventBus初始化--->绑定
        EventBus.getDefault().register(this);
        //初始化
        mShareAPI = UMShareAPI.get(ProgrameLiveDetailActivity.this);
        //可以更改默认的session启动时间,默认30秒
        //初始化控件
        initView();
        //tablayout与fragment的监听
        tabFragmentListener();
        //下载解析json
        LoadJson();
        //分享登录点击事件
        //
        shareLoginOnclick();
    }

    private void tabFragmentListener() {
        String[] ZTitles = getResources().getStringArray(R.array.live_detail);
        List<String> titles = new ArrayList<>();
        List<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < ZTitles.length; i++) {
            Fragment fragment = FactoryFragment.createFragment(i);
            mTab.getTabAt(i);
            titles.add(ZTitles[i]);
            fragments.add(fragment);
        }
        //创建适配器
        final MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(),fragments,titles);
        assert adapter != null;
        //设置viewpager适配器
        mVp.setAdapter(adapter);
        //联动监听
        mTab.setupWithViewPager(mVp);
    }

    //第三方登录监听
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
            Log.i("TAG","data--->"+data.toString());
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };
    //第三方分享监听
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);

            Toast.makeText(ProgrameLiveDetailActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ProgrameLiveDetailActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ProgrameLiveDetailActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private void shareLoginOnclick() {
        mBar.inflateMenu(R.menu.over);
        mBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.action_shape://分享
                        //设置分享的平台
                        SHARE_MEDIA[] list = new SHARE_MEDIA[]{
                                SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.DOUBAN,
                                SHARE_MEDIA.EMAIL, SHARE_MEDIA.SMS, SHARE_MEDIA.RENREN, SHARE_MEDIA.YNOTE
                        };

                        new ShareAction(ProgrameLiveDetailActivity.this)
                                .setDisplayList(list)//设置分享的平台列表
                                .withText("主播连接")//分享的内容
                                .withTitle("主播的标题")//分享的标题
                                //.withTargetUrl(url)//分享一个链接
                                //.addButton()
                                .setCallback(umShareListener)//分享的监听
                                .open();//打开分享面板
                        break;
                    case R.id.action_report://登录
                        ArrayAdapter<String> dialogAdapter = new ArrayAdapter<>(ProgrameLiveDetailActivity.this,android.R.layout.simple_list_item_1);
                        dialogAdapter.add("游戏外服、外挂");
                        dialogAdapter.add("欺诈广告");
                        dialogAdapter.add("色情、低俗表演");
                        dialogAdapter.add("转播未获得授权的内容");
                        dialogAdapter.add("持续谩骂");
                        dialogAdapter.add("反动政治");
                        dialogAdapter.add("其他违规行为");
                        new AlertDialog.Builder(ProgrameLiveDetailActivity.this)
                                .setTitle("请选择举报类型")
                                .setAdapter(dialogAdapter, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int position) {

                                    }
                                })
                                .setNegativeButton("取消", null)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Toast.makeText(ProgrameLiveDetailActivity.this,"举报成功",Toast.LENGTH_LONG).show();

                                    }
                                })
                                .setCancelable(false)
                                .show();
                        //初始化
                        //UMShareAPI mShareAPI = UMShareAPI.get( this );
                        //进行授权验证  QQ
//                        mShareAPI.doOauthVerify(ProgrameLiveDetailActivity.this, SHARE_MEDIA.QQ, umAuthListener);
                        //获取用户信息
//                        mShareAPI.getPlatformInfo(ProgrameLiveDetailActivity.this, SHARE_MEDIA.QQ, umAuthListener);
                        //新浪
//                        mShareAPI.doOauthVerify(ProgrameLiveDetailActivity.this, SHARE_MEDIA.SINA, umAuthListener);
                        //获取用户信息
//                        mShareAPI.getPlatformInfo(ProgrameLiveDetailActivity.this, SHARE_MEDIA.SINA, umAuthListener);
                        break;
                }
                return false;
            }
        });
    }

    private void LoadJson() {
        new Thread(new Runnable() {

            private String url;
            private String data;

            @Override
            public void run() {
                String str = getSystemTime.getTime(Configs.JSON_URL_LIVE_DETAIL);
                url = str.replace("#d", uid);
                //传递给MainActivity进行展示
                if (url != null) {
                    //利用EventBus传递消息
                    EventBus.getDefault().post(new FragmentBean(url));
//                    finish();
                }
                data = OkHttpUtils.getJsonFromUrl(url);
                Log.i("TAG","json数据="+ data);
                try {
                    JSONObject object = new JSONObject(data);
                    view = object.getInt("view");
                    nick = object.getString("nick");
                    title = object.getString("title");
                    JSONArray array = object.getJSONArray("hot_word");
                    JSONObject obj = object.getJSONObject("live");
                    JSONObject ws = obj.getJSONObject("ws");
                    JSONObject hls = ws.getJSONObject("hls");
                    JSONObject str1 = hls.getJSONObject("4");
                    String videourl = str1.getString("src");
                    list = new ArrayList<>();
                    for (int i = 0; i < array.length(); i++) {
                        String content = array.getString(i);
                        list.add(content);
                    }
                    Log.i("TAG","............................list="+ list.size());

                    avator = object.getString("avator");
//                    Glide.with(ProgrameLiveDetailActivity.this).load(avator).placeholder(R.mipmap.ic_launcher).into(iv_avator);
//                    bean = new ProgrameLiveDetailBean(view, nick, title, avator);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                }
        }).start();
    }

    private void initView() {
        mVideo = (VideoView) findViewById(R.id.live_detail_Videoview);
        iv_avator = (ImageView) findViewById(R.id.live_detail_iv_avator);
        tv_view = (TextView) findViewById(R.id.live_detail_tv_view);
        tv_nick = (TextView) findViewById(R.id.live_detail_tv_nick);
        tv_title = (TextView) findViewById(R.id.live_detail_tv_title);
        mBar = (Toolbar) findViewById(R.id.live_detail_toolbar);
        mVp = (ViewPager) findViewById(R.id.live_detail_viewpager);
        mTab = (TabLayout) findViewById(R.id.live_detail_tablayout);
        findViewById(R.id.live_detail_bt_hot).setOnClickListener(this);
        findViewById(R.id.live_detail_bt_send).setOnClickListener(this);
        findViewById(R.id.live_detail_bt_focus).setOnClickListener(this);
        //获取对象
        Intent intent = getIntent();
//        ProgrameDetailBean.DataBean bean = (ProgrameDetailBean.DataBean) intent.getSerializableExtra("detail");
         uid = intent.getStringExtra("detail");
        //获取房间号
//        uid = String.valueOf(bean.getUid());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.live_detail_bt_hot://热
                Toast.makeText(ProgrameLiveDetailActivity.this,"热",Toast.LENGTH_LONG).show();
                LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View convertview = layoutInflater.inflate(R.layout.hot_list_item, null);
                PopupWindow mPopWindow = new PopupWindow(convertview,400,300);
                // 使其聚集
                //mPopWindow.setFocusable(true);
                // 设置允许在外点击消失
                mPopWindow.setOutsideTouchable(true);
                mPopWindow.showAtLocation(convertview,Gravity.LEFT/Gravity.BOTTOM,10,800);
                ListView hLv = (ListView)convertview.findViewById(R.id.hot_lv);
                List<String> data = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    data.add("热点语句" + i);
                }
                assert hLv != null;
                adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
                hLv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                String str = String.valueOf(view);
                tv_nick.setText(nick);
                tv_title.setText(title);
                tv_view.setText(str);
//                int conut = str.length() - 4;
//                if(str.length() >= 5){
//                    tv_view.setText(str.substring(0,conut) + "." + str.substring(conut,conut+1) + "万");
//                }else {
//                    tv_view.setText(str);
//                }
                break;
            case R.id.live_detail_bt_send://发送弹幕
                Toast.makeText(ProgrameLiveDetailActivity.this,"发送",Toast.LENGTH_LONG).show();

                break;
            case R.id.live_detail_bt_focus://关注-->实现收藏到数据库
                Toast.makeText(ProgrameLiveDetailActivity.this,"关注",Toast.LENGTH_LONG).show();

                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定
        EventBus.getDefault().unregister(this);
    }
}
